package november.search;

import java.util.Arrays;

/**
 * @author huangxin
 * @date 2019/11/19-19:48
 */
public class FibonacciSearch {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int index = fibonacciSearch(arr, 1);
        if (index == -1) {
            System.out.println("没有找到");
        } else {
            System.out.println("下标为" + index);
            System.out.println(arr[index]);
        }

        System.out.println(Arrays.toString(fib()));

//        System.out.println(binarySearch2(arr, 0, arr.length - 1, 6));
    }


    public static int fibonacciSearch(int[] arr, int value) {
        int low = 0;
        int high = arr.length - 1;
        int k = 0; //斐波那契分割数值的下标
        int mid = 0;
        int[] fib = fib();


        //获取斐波那契可以分割的数值下标
        while (high > fib[k] - 1) {
            k++;
        }

        //因为fib[k]的值可能大于 arr 的长度,因此我们需要使用Arrays类,构造一个新的数组,长度=fib[k],不足的 部分使用0填充
        int[] temp = Arrays.copyOf(arr, fib[k]);

        //用arr[high]填充temp,扩充成一个可以使用斐波那契查找的数组
        for (int i = high + 1; i < temp.length; i++) {
            temp[i] = arr[high];
        }

        //使用循环查找数据
        while (low <= high) {
            mid = low + fib[k - 1] - 1;
            if (value < temp[mid]) {//向左边查找
                high = mid - 1;
                //即下次循环 mid=fib[k-1-1]-1
                k--;//黄金分割数变小
            } else if (value > temp[mid]) {//向右边查找
                low = mid + 1;
                //即下次循环 mid=fib[k-1-2]-1
                k -= 2;//黄金分割数变小
            } else {
                if (mid <= high) {
                    return mid;
                } else {
                    return high;
                }
            }
        }
        return -1;
    }


    private static int maxSize = 100;

    public static int[] fib() {
        //构建斐波那契数列
        int[] fib = new int[maxSize];
        fib[0] = 1;
        fib[1] = 1;
        for (int i = 2; i < fib.length; i++) {
            fib[i] = fib[i - 1] + fib[i - 2];
        }

        return fib;
    }
}
